package com.zhu.SupermarketInventoryManagement.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhu.SupermarketInventoryManagement.dao.IAdminDao;
import com.zhu.SupermarketInventoryManagement.model.DO.AdminDO;
import com.zhu.SupermarketInventoryManagement.model.QO.AdminQO;
import com.zhu.SupermarketInventoryManagement.model.ResultCommon;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class AdminService {

    @Resource
    IAdminDao iAdminDao;

    public ResultCommon list(AdminQO admin) {
        Page<AdminDO> page = new Page<>(admin.getPage(), admin.getLimit());
        IPage<AdminDO> result = iAdminDao.page(page);
        List<AdminDO> records = result.getRecords();
        //result.getTotal()表示查询到的结果总数，result.getRecords()表示查询到的结果
        return ResultCommon.<List<AdminDO>>builder().code(0).count(result.getTotal()).data(records).build();
    }

    public ResultCommon<Object> update(AdminQO adminQO) {
        //获取员工id
        List<AdminDO> list = iAdminDao.list();
        Integer id = 1;
        if (!list.isEmpty()) {
            for (AdminDO adminDO : list) {
                id = adminDO.getId() + 1;
            }
        }

        ResultCommon<Object> resultCommon = new ResultCommon<>();
        UpdateWrapper<AdminDO> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", adminQO.getId());
        AdminDO adminDO = AdminDO.builder()
                .id(id)
                .username(adminQO.getUsername())
                .password(adminQO.getPassword())
                .build();
        iAdminDao.update(adminDO, wrapper);
        resultCommon.setCode(0);
        return resultCommon;
    }

    public ResultCommon<Object> delete(String id) {
        ResultCommon<Object> resultCommon = new ResultCommon<>();
        iAdminDao.removeById(id);
        System.out.println(id);
        return resultCommon;
    }

    public ResultCommon add(AdminQO adminQO) {
        //获取员工id
        List<AdminDO> list = iAdminDao.list();
        Integer id = 1;
        if (!list.isEmpty()) {
            for (AdminDO adminDO : list) {
                id = adminDO.getId() + 1;
            }
        }

        ResultCommon<Object> resultCommon = new ResultCommon<>();
        AdminDO adminDO = AdminDO.builder()
//                .id(id)
                .username(adminQO.getUsername())
                .password(adminQO.getPassword())
                .build();
        try {
            iAdminDao.save(adminDO);
            resultCommon.setCode(0);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            resultCommon.setCode(500);
        }
        return resultCommon;
    }
}
